import logging
from base64 import b64encode, b64decode
import os
import datetime
import time
import uuid
from hashlib import md5
from logging.handlers import TimedRotatingFileHandler




def get_logger(name, level=None):
    logger = logging.getLogger(name)
    if len(logger.handlers) == 2:
        return logger
    logger_file = os.path.join(LOG_PATH, "{0}.log".format(name))

    logging_format = logging.Formatter(LOG_FORMAT)

    logger_level = level or LOG_LEVEL

    file_handler = TimedRotatingFileHandler(logger_file, when="D", backupCount=30)
    file_handler.setLevel(logger_level)
    file_handler.setFormatter(logging_format)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logger_level)
    console_handler.setFormatter(logging_format)

    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    logger.setLevel(logger_level)
    return logger


def get_uuid():
    return str(uuid.uuid1())


def get_ts():
    return int(time.time() * 1e3)


def base64_encode(content):
    if isinstance(content, str):
        content = content.encode()
    return b64encode(content).decode()


def base64_decode(text):
    if isinstance(text, str):
        content = text.encode()
    else:
        content = text
    try:
        return b64decode(content)
    except:
        return None


def get_md5_from_str(text):
    if isinstance(text, str):
        text = text.encode()
    m5 = md5()
    m5.update(text)
    return m5.hexdigest()


def create_save_path(base_path, suffix=''):
    save_dir = os.path.join(base_path, datetime.datetime.now().strftime("%Y-%m-%d"))
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    save_path = os.path.join(save_dir, str(uuid.uuid4()) + suffix)
    return save_path
